﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net.WebSockets;
using XmppDotNet.Xmpp;
using XmppDotNet;
using XmppDotNet.Transport;
using XmppDotNet.Transport.Socket;
using XmppDotNet.Extensions.Client.Presence;
using System.Reactive.Linq;
using XmppDotNet.Xmpp.Base;
using XmppDotNet.Xml;
using XmppDotNet.Extensions.Client.Message;
using System.Text;
using Microsoft.AspNetCore.SignalR;

namespace XmppWebTest.Controllers
{
    [Route("api/chat")]
    public class ChatWebSocketController : ControllerBase
    {
        private static XmppClient _xmppClient;
        private readonly IHubContext<ChatHub> _chatHubContext;

        public ChatWebSocketController(IHubContext<ChatHub> chatHubContext)
        {
            _chatHubContext = chatHubContext;
            if (_xmppClient == null)
            {
                InitXmppClient();
            }
        }

        private void InitXmppClient()
        {
            _xmppClient = new XmppClient(
                conf =>
                {
                    conf.UseSocketTransport(new StaticNameResolver(new Uri("tcp://47.117.74.76:5222")))
                    .WithCertificateValidator(new AlwaysAcceptCertificateValidator());
                }
            )
            {
                Jid = "jxh@izeellvnf5htoqz", // XMPP 用户 JID
                Password = "hilink123456"
            };

            _xmppClient.XmppXElementReceived
                .Where(el => el is Message)
                .Subscribe(el =>
                {
                    var message = el.Cast<Message>();
                    var sender = message.From;
                    var text = message.Body;

                    Debug.WriteLine($"收到消息：{sender}: {text}");

                    // 将消息转发给所有连接的 SignalR 客户端
                    var msg = $"{sender}: {text}";
                    BroadcastMessage(msg);
                });

            _xmppClient.ConnectAsync().Wait();
            _xmppClient.SendPresenceAsync(Show.Chat, "在线").Wait();
        }

        // 将消息广播到所有 SignalR 客户端
        private async void BroadcastMessage(string message)
        {
            // 通过 SignalR 将消息广播到所有连接的客户端
            await _chatHubContext.Clients.All.SendAsync("ReceiveMessage", "XMPP", message);
        }

        // 发送消息到 XMPP 客户端
        [HttpPost("sendToXmpp")]
        public async Task<IActionResult> SendMessageToXmpp([FromBody] string message)
        {
            if (_xmppClient != null && !string.IsNullOrEmpty(message))
            {
                await _xmppClient.SendChatMessageAsync("zzh@izeellvnf5htoqz", message);  // 向 XMPP 发送消息
                return Ok(new { Status = "Message sent to XMPP" });
            }
            return BadRequest("XMPP client not initialized or message is empty");
        }

        // 接收前端消息并通过 XMPP 客户端转发
        [HttpPost("sendToClient")]
        public async Task<IActionResult> SendMessageToClient([FromBody] string message)
        {
            // 转发到 XMPP 服务器
            await _xmppClient.SendChatMessageAsync("zzh@izeellvnf5htoqz", message);

            // 通过 SignalR 广播到所有客户端
            BroadcastMessage($"你：{message}");

            return Ok(new { Status = "Message sent to XMPP and clients" });
        }
    }
}
